package com.llsly.wearabledataviz.service;

import com.llsly.wearabledataviz.model.WearableData;
import com.llsly.wearabledataviz.repository.WearableDataRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class WearableDataService {
    
    @Autowired
    private WearableDataRepository repository;
    
    @Autowired
    private SimpMessagingTemplate messagingTemplate;
    
    public void saveData(WearableData data) {
        // 检测异常
        detectAnomalies(data);
        // 保存数据
        repository.save(data);
        // 通过WebSocket推送数据
        messagingTemplate.convertAndSend("/topic/wearable-data", data);
    }
    
    public List<WearableData> getDataByTimeRange(String deviceId, LocalDateTime start, LocalDateTime end) {
        return repository.findByDeviceIdAndTimestampBetween(deviceId, start, end);
    }
    
    public List<WearableData> getAnomalies(LocalDateTime start, LocalDateTime end) {
        return repository.findAnomaliesBetween(start, end);
    }
    
    private void detectAnomalies(WearableData data) {
        // 简单的心率异常检测逻辑
        if (data.getHeartRate() != null) {
            if (data.getHeartRate() > 100) {
                data.setIsAnomaly(true);
                data.setAnomalyDescription("心率过高");
            } else if (data.getHeartRate() < 60) {
                data.setIsAnomaly(true);
                data.setAnomalyDescription("心率过低");
            } else {
                data.setIsAnomaly(false);
                data.setAnomalyDescription(null);
            }
        }
    }
} 